package com.zretc.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.Statement;
import com.zretc.dao.UsersDao;
import com.zretc.entity.Jianli;
import com.zretc.entity.Users;
import com.zretc.tools.DB2;
import com.zretc.tools.DBTools;

import com.zretc.tools.PageData;



public class UsersDaoImpl implements UsersDao {

	@Override
	public boolean addUsers(Users u) {
		// TODO Auto-generated method stub
		String sql = "insert into users values(null,?,?)";
		return DBTools.exUpdate(sql,u.getUsername(),u.getPwd())>0;
	}

	@Override
	public Users getUsersByUsername(String username) {
		// TODO Auto-generated method stub
		String sql = "select username,pwd from users where username= ?";
		List<Users> list=(List<Users>)DBTools.exQuery(sql, Users.class, username);
		
		if(list.size()==0) {
			return null;
		}
		return list.get(0);
	}
	

	@Override
	public List<Users> getUsers(String keywords) {
		String sql="select * from users where username like ?";
		List<Users> list = (List<Users>) DBTools.exQuery(sql, Users.class, "%"+keywords+"%");
		return list;
	}

	@Override
	public PageData<Users> getUsersByPage(int page, int pageSize, String keywords) {
		// TODO Auto-generated method stub
		PageData<Users> pd = DBTools.exQueryByPage("select * from users where username like ?",Users.class, page, pageSize, "%"+keywords+"%");
		return pd;
	}

	@Override
	public Users login(String username, String pwd) {
Users users = null;
		
		Connection conn = DB2.getConnection();
		
		String sql = "select * from users where username = ? and pwd = ?";
		try {
			
			PreparedStatement ps = conn.prepareStatement(sql);
			
			ps.setString(1, username);
			ps.setString(2, pwd);
			
			ResultSet rs = ps.executeQuery();
			
			if(rs.next()){
				
				users = new Users();
				
				
				users.setUsername(rs.getString("username"));
				users.setPwd(rs.getString("pwd"));
				
			}
			
			rs.close();
			
			ps.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			DB2.closeConnection(conn);
		}
		return users;
	}



}
